<template>
  <div ref="containerRef" class="tdt-cesium-map"></div>

</template>

<script setup lang="ts">
import { ref, onMounted, onBeforeUnmount, watch } from 'vue';
import * as Cesium from 'cesium';
import 'cesium/Build/Cesium/Widgets/widgets.css';

interface Props {
  token: string;
  lon: number;
  lat: number;
  height?: number;
}

const props = withDefaults(defineProps<Props>(), {
  height: 15000
});

const containerRef = ref<HTMLElement | null>(null);
let viewer: Cesium.Viewer | null = null;
let markerEntity: Cesium.Entity | null = null;

function createTiandituBaseProvider(token: string) {
  // 天地图矢量底图（原版地图）
  return new Cesium.UrlTemplateImageryProvider({
    url: `https://t{s}.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${token}`,
    subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
    minimumLevel: 0,
    maximumLevel: 18,
    credit: '天地图矢量'
  });
}

function createTiandituLabelProvider(token: string) {
  // 天地图矢量注记
  return new Cesium.UrlTemplateImageryProvider({
    url: `https://t{s}.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${token}`,
    subdomains: ['0', '1', '2', '3', '4', '5', '6', '7'],
    minimumLevel: 0,
    maximumLevel: 18,
    credit: '天地图注记'
  });
}

const initViewer = () => {
  if (!containerRef.value) return;

  viewer = new Cesium.Viewer(containerRef.value, {
    animation: false,
    timeline: false,
    baseLayerPicker: false,
    geocoder: false,
    homeButton: false,
    sceneModePicker: false,
    navigationHelpButton: false,
    fullscreenButton: false,
    infoBox: false,
    selectionIndicator: false
  });

  // 移除默认底图
  viewer.imageryLayers.removeAll();

  // 添加天地图原版（矢量）底图
  const baseProvider = createTiandituBaseProvider(props.token);
  viewer.imageryLayers.addImageryProvider(baseProvider);

  // 添加天地图标注图层
  const labelProvider = createTiandituLabelProvider(props.token);
  if (labelProvider) {
    viewer.imageryLayers.addImageryProvider(labelProvider);
  }

  // 禁用从太空旋转进入的动画效果，直接定位
  viewer.camera.setView({
    destination: Cesium.Cartesian3.fromDegrees(props.lon, props.lat, props.height)
  });

  // 初始化定位点标注
  updateLocationMarker(props.lon, props.lat);

  // 隐藏 Cesium 版权信息（如需显示可移除此行对应样式）
  if ((viewer.cesiumWidget.creditContainer as any)) {
    (viewer.cesiumWidget.creditContainer as HTMLElement).style.display = 'none';
  }
};

function updateLocationMarker(lon: number, lat: number) {
  if (!viewer) return;
  const position = Cesium.Cartesian3.fromDegrees(lon, lat, 0);
  if (!markerEntity) {
    markerEntity = viewer.entities.add({
      id: 'default-position-marker',
      position,
      billboard: {
        image: '/images/position_default.png',
        verticalOrigin: Cesium.VerticalOrigin.BOTTOM,
        scale: 1,
        disableDepthTestDistance: Number.POSITIVE_INFINITY
      }
    });
  } else {
    // 更新已有标注位置
    // 使用 ConstantPositionProperty 以符合类型要求
    markerEntity.position = new Cesium.ConstantPositionProperty(position);
  }
}

function flyTo(lon: number, lat: number, height = 15000) {
  if (!viewer) return;
  viewer.camera.flyTo({
    destination: Cesium.Cartesian3.fromDegrees(lon, lat, height),
    duration: 1.2
  });
}

function getViewer() {
  return viewer;
}

// 监听经纬度变化，更新标注
watch(
  () => [props.lon, props.lat] as const,
  ([lon, lat]) => {
    updateLocationMarker(lon, lat);
  }
);

onMounted(() => {
  initViewer();
});

onBeforeUnmount(() => {
  if (viewer) {
    viewer.destroy();
    viewer = null;
    markerEntity = null;
  }
});

defineExpose({ flyTo, getViewer, updateLocationMarker });
</script>

<style scoped>
.tdt-cesium-map {
  position: absolute;
  inset: 0;
}
</style>

<style>
/* 全局隐藏 Cesium 自带的 logo/版权（如需显示可移除） */
.cesium-widget-credits {
  display: none !important;
}
</style>
